﻿using AutoTest.Common.Extension;
using NPOI.SS.UserModel;

namespace AutoTest.Common.ExcelExport
{
    /// <summary>
    /// Excel导出的扩展方法
    /// </summary>
    public static class ExcelExportExtension
    {
        /// <summary>
        /// 渲染表格
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="sheet">sheet表格</param>
        /// <param name="rowIndex">开始行</param>
        /// <param name="colIndex">开始列</param>
        /// <param name="dataList">数据</param>
        /// <param name="prevColumns">前置列</param>
        /// <param name="lastColumns">后置列</param>
        /// <returns></returns>
        public static IWorkbook RenderSheet<T>(this ISheet sheet,  
            int rowIndex, int colIndex, IEnumerable<T> dataList, 
            List<ExportHeaderAttribute> prevColumns = null!, List<ExportHeaderAttribute> lastColumns = null!)
        {
            ExportHelper.RenderSheet<T>(sheet, rowIndex, colIndex, dataList, prevColumns, lastColumns);
            return sheet.Workbook;
        }

        /// <summary>
        /// 渲染表格
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="workbook">Excel对象</param>
        /// <param name="sheetName">Sheet名称</param>
        /// <param name="rowIndex">开始行</param>
        /// <param name="colIndex">开始列</param>
        /// <param name="dataList">数据</param>
        /// <param name="prevColumns">前置列</param>
        /// <param name="lastColumns">后置列</param>
        /// <returns></returns>
        public static IWorkbook RenderSheet<T>(this IWorkbook workbook,
            string sheetName = "",int rowIndex = 0,int colIndex = 0,IEnumerable<T> dataList = null!,
            List<ExportHeaderAttribute> prevColumns = null!, List<ExportHeaderAttribute> lastColumns = null!)
        {
            if (sheetName.IsEmpty()) sheetName = "sheet";
            string newSheetName = sheetName;
            int index = 0;
            while (workbook.GetSheet(newSheetName) != null)
            {
                newSheetName = $"{sheetName}{index++}";
            }
            sheetName = newSheetName;
            ISheet sheet = workbook.CreateSheet(sheetName);
            workbook = RenderSheet<T>(sheet, rowIndex, colIndex, dataList ?? [], prevColumns, lastColumns);
            return workbook;
        }
    }
}
